<template>
    <van-nav-bar title="注册" left-text="返回" left-arrow @click-left="() => { $router.push('/') }" fixed />
    <div style="height: 45px;"></div>

    <van-form @submit="onSubmit">
        <van-cell-group inset>
            <van-field v-model="username" name="username" label="用户名" placeholder="用户名"
                :rules="[{ required: true, message: '请填写用户名' }]" />
            <van-field v-model="password" :type="status==true?'text':'password' " name="password" label="密码" placeholder="密码"
                :rules="[{ required: true, message: '请填写密码' }]" />

            <template #button>
                <van-icon name="eye-o" style="font-size: 25px;" @click=" status=!status" />
            </template>


                <van-field v-model="phone" name="pattern" label="手机号" placeholder="正则校验"
                    :rules="[{ pattern, message: '请输入手机号' }]" />

                <van-field v-model="yzm" name="yzm" label="验证码" placeholder="请输入验证码"
                    :rules="[{ required: true, message: '请输入验证码' }]" />

        </van-cell-group>

        <div style="margin: 16px;">
            <van-button round block type="primary" @click="yzmbtn" class="yzmtime">
                获取验证码
            </van-button>
        </div>

        <div style="margin: 16px;">
            <van-button round block type="primary" native-type="submit">
                用户注册
            </van-button>
        </div>
    </van-form>
</template>

<script setup>

import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { showSuccessToast, showFailToast } from 'vant';
import { registerApi } from '@/api/api'
const router = useRouter();
let username = ref('')
let password = ref('')
let phone = ref('')
let pattern = /^1[3-9]\d{9}$/
const onSubmit = () => {
    registerApi(username.value, password.value).then(res => {
        // console.log('注册数据',res);
        if (res.data.code == 0) {
            showSuccessToast('注册成功')
            router.push('/login')
        }
        else {
            showFailToast('注册失败')
        }
    })
}
let yzm = ref('')
let timer;
let time = ref(5)
const yzmbtn = () => {
    yzm.value = Math.floor(Math.random() * 1000000)

    let yzmtime = document.querySelector('.yzmtime')
    timer = setInterval(() => {
        time.value--;
        yzmtime.innerHTML = time.value + '秒'
        if (time.value == 0) {
            clearInterval(timer);
            time.value = 5;
            yzmtime.innerHTML = '重新获取'
        }
    }, 1000);
}
</script>

<style lang="scss" scoped></style>